<template>
  <q-modal v-model="modalVisible" :header="header" :submitText="$t('Confirm')" width="420" @beforeClose="beforeClose"
           @confirm="submitForm">
    <AreaTextAttrs ref="areaText" :readonly="true" :rowInfo="shapeForm" :type="currentAction"></AreaTextAttrs>
  </q-modal>
</template>

<script setup>
import { i18n } from 'boot/i18n'
import { createText, dash, drawAreaByCoord, fillUndoList } from '../utils/MouseEvent'
import AreaTextAttrs from '../AttrTools/AreaTextAttrs.vue'
import {
  attrsModal, clearOperShape, currentAction, exportAttrs, setAttrsModal, setCanRedo, setCanUndo, shapeAttrs
} from '../utils/KonvaEvent'
import { computed, onUnmounted, provide, ref, watchPostEffect } from 'vue'

defineProps({ openedMap: Object })

const shapeForm = ref({})
const areaText = ref(null)
const modalVisible = ref(false)
const header = computed(() => {
  if (currentAction.value === 'area') return i18n.t('MapCore.AddAreaTitle')
  if (currentAction.value === 'text') return i18n.t('MapCore.AddText')
  return ''
})
watchPostEffect(() => attrsModal.value && ['createArea', 'createText'].includes(shapeAttrs.value?.action) && initData())
onUnmounted(() => setAttrsModal(false))
const initData = () => {
  shapeForm.value = shapeAttrs.value
  shapeForm.value.textFontSize = shapeAttrs.value.textFontSize || 14
  modalVisible.value = true
}
const beforeClose = () => {
  setAttrsModal(false)
  modalVisible.value = false
  clearOperShape('deleteArea')
}
const updateShapeAttrs = (form, done) => {
  form.action = currentAction.value
  const { CANVAS, redoList = [], undoList = [] } = exportAttrs()
  const { border, fill, textColor, height } = form
  const dashArea = border === 'dash' ? dash : [], stroke = border === 'none' ? '' : form.stroke
  const operInfo = currentAction.value === 'area' ? drawAreaByCoord(CANVAS,
    { ...form, border, height: -height, dash: dashArea, fill, stroke, textColor }) : createText(CANVAS,
    { ...form, type: 'text', fill: textColor, textColor })
  clearOperShape('deleteArea')
  if (!operInfo) return done && done()
  if (currentAction.value === 'area') fillUndoList(undoList, redoList, operInfo, 'createArea')
  else if (currentAction.value === 'text') fillUndoList(undoList, redoList, [operInfo], 'createText')
  setCanUndo(undoList.length > 0)
  setCanRedo(redoList.length > 0)
  clearOperShape('move')
  done && done()
}
provide('updateShapeAttrs', updateShapeAttrs)
const submitForm = mDone => areaText.value && areaText.value.submitAjax(mDone)
</script>